package net.yunzhanyi.common.web.util;


import net.yunzhanyi.common.core.utils.StringUtils;
import net.yunzhanyi.common.web.config.YunzhanyiConfig;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author TingChang
 * @code FileUploadUtils
 * @date 2021/11/7
 * description:
 */

@Component
public class FileUploadUtils {

    /**
     * @param file     文件
     * @param path     文件存放路径
     * @param fileName 保存的文件名
     * @return
     */

    @Autowired
    private YunzhanyiConfig yunzhanyiConfig;

    public String upload(MultipartFile file, String path, String fileName) {

        String relativePath = path + "/"+ DateUtils.datePath()+"/" + fileName;
        //确定上传的文件名
        String realPath = yunzhanyiConfig.getResourcePath() + relativePath;
        System.out.println("上传文件：" + realPath);

        File dest = new File(realPath);
        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            //保存文件
            file.transferTo(dest);
            return relativePath;
        } catch (IllegalStateException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static String getExtension(MultipartFile file)
    {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension))
        {
            extension = MimeTypeUtils.getExtension(file.getContentType());
        }
        return extension;
    }
}

